package com.stark.commons.spring.web.support.exception;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import lombok.extern.slf4j.Slf4j;

/**
 * {@link MethodArgumentTypeMismatchException} 异常处理器。
 * <p>返回 <code>400</code>状态码及错误信息。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Slf4j
public class MethodArgumentTypeMismatchExceptionHandler implements ExceptionHandler {

	@Override
	public boolean instanceofException(Exception ex) {
		return ex instanceof MethodArgumentTypeMismatchException;
	}

	@Override
	public ResponseEntity<String> handle(Exception ex) {
		String errmsg = "";
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (requestAttributes != null) {
			HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
			try {
				String uri = request.getRequestURI() + (StringUtils.isBlank(request.getQueryString()) ? "" : "?" + URLDecoder.decode(request.getQueryString(), "UTF-8"));
				errmsg = request.getMethod() + " '" + uri + "' : " + ex.getMessage();
			} catch (UnsupportedEncodingException e) {
				// do nothing
			}
		}
		log.error(errmsg, ex);
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errmsg);
	}

}
